<template>
  <div>
    <!--条件筛选-->
    <TopFilter ref="topfilter" :list="topFilterList" :cols="4" labelWidth="85" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <!--操作 -->
    <button-area :style="{ paddingLeft: '80px' }"></button-area>
    <!-- 列筛选-->
    <!-- :fetchapi="fetchApi" -->
    <FilterTable
      ref="table"
      columnsRef="zxUsedCardQuality"
      :columns="columns"
      :params="fetchParams"
      :fetchapi="fetchApi"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectData"
      :onSyncTableData="tableChangeFun"
    >
      <template slot="controls" slot-scope="props">
        <multiuse-button type="primary" :click="exportHandle.bind(this)">导出</multiuse-button>
      </template>
      <!--列操作-->
      <!-- <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="addHandle">新增</el-button>
        <AjaxButton size="small" type="danger" :click="removeHandler">删除</AjaxButton>
      </template> -->
    </FilterTable>
    <!-- 选择经销商 -->
    <BaseDialog :visible.sync="dealerAction.visible" :title="dealerAction.title" destroyOnClose :containerStyle="{ height: 'calc(100% - 70px)', overflow: 'auto', paddingBottom: '70px' }">
      <searchDealerPanel :type="dealerAction.type" :row="dealerAction.data" @close="closeDealerDialog" @saveDialog="saveDealerDialog" />
    </BaseDialog>
    <!--抽屉 -->
    <Drawer :visible.sync="visible" :title="dialogTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <QualityModal :type="handleType" :rowData="formData" @close="closeHandler" />
    </Drawer>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { getOwnerCode } from '@/assets/js/auth';
import { getNameByIds } from '@/api/repair/common';
import { getMonthReportOEM, exportMonthReportBJ } from '@/api/part/report/partreport';
import moment from 'moment';
import { dealerMixin } from '@/pages/repair/batchEventManagement/dealerMixin';
import { dealerInfoByAllInfo } from '@/api/part/allocation';
import { arrayObjDeWeight } from '@/utils/index';
import searchDealerPanel from '@/pages/repair/mileageDateChange/mileageApprove/searchDealerPanel';
// import { getUsedCardQualitys } from '@/api/usedcar/basic/qaproduct'; // 页面调用的的方法,对应的路径连接后台

export default {
  name: 'zxUsedCardQuality',
  components: {
    searchDealerPanel
  },
  mixins: [dictionary, dealerMixin],
  data() {
    this.conf = { add: '新增', delete: '删除', edit: '编辑', show: '显示' };
    return {
      topFilterList: this.createTopFilterList(),
      fetchParams: { xhrAbort: true },
      visible: false,
      visible1: false,
      dialogTitle: '',
      // fetchApi: getUsedCardQualitys,
      columns: this.createTableColumns(),
      handleType: '',
      formData: {},
      dealerAction: { type: '', visible: false, title: '选择经销商', data: null },
      fetchApi: getMonthReportOEM,
      tableData: [],
      ids: []
    };
  },
  mounted() {
    // 分页
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.getAllOwnerCode();
  },
  methods: {
    createTopFilterList() {
      return [
        // {
        //   type: 'MULTIPLE_SELECT',
        //   label: '经销商',
        //   fieldName: 'ownerCode',
        //   filterable: true,
        //   itemList: []
        // },
        // {
        //   type: 'TEXT_AREA',
        //   label: '经销商代码',
        //   fieldName: 'dealerCode',
        //   placeholder: '请输入',
        //   maxlength: '',
        //   maxRows: 2
        // },
        {
          type: 'DATE',
          label: '请选择年月',
          fieldName: 'month',
          placeholder: '请选择...',
          dateType: 'month'
        }
      ];
    },
    createTableColumns() {
      return [
        // {
        //   title: '操作',
        //   dataIndex: 'column-action',
        //   width: 60,
        //   fixed: 'left',
        //   render: props => {
        //     return (
        //       <div>
        //       <el-button size="mini" type="text" onClick={() => this.editHandle(props.row)}>
        //     编辑
        //     </el-button>
        //     </div>
        //   );
        //   }
        // },
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        // {
        //   title: '经销商代码',
        //   dataIndex: 'OWNER_CODE',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        // {
        //   title: '经销商名称',
        //   dataIndex: 'ownerName',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'checkbox',
        //   dictItems: [],
        //   filterItems: []
        // },
        {
          title: '年份',
          dataIndex: 'reportYear',
          sorter: true,
          filter: true
        },
        {
          title: '月份',
          dataIndex: 'reportMonth',
          sorter: true,
          filter: true
        },
        {
          title: '油电属性',
          dataIndex: 'powerType',
          dictItems: this.createDictList(5000),
          sorter: true,
          filter: true
        },
        {
          title: '制单人',
          dataIndex: 'createdBy',
          sorter: true,
          dictItems: [],
          filter: true
        },
        {
          title: '制单时间',
          dataIndex: 'createdAt',
          sorter: true,
          filter: true
        },
        {
          title: '总进厂台次',
          dataIndex: 'sumInOrder',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '保养进厂台次',
          dataIndex: 'byInOrder',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '维修进厂台次',
          dataIndex: 'repairInOrder',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '总产值',
          dataIndex: 'sumAmount',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '期末库存金额',
          dataIndex: 'closeAmount',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '期末库存品种',
          dataIndex: 'partTypeClose',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '期初库存金额',
          dataIndex: 'openAmount',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '期初库存品种',
          dataIndex: 'partTypeOpen',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '机油库存金额',
          dataIndex: 'oilCostAmount',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '机油库存品种',
          dataIndex: 'oilTypeCounts',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '当月入库金额',
          dataIndex: 'stockInAmount',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '当月入库品种',
          dataIndex: 'inTypeCounts',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '当月保养出库金额',
          dataIndex: 'byOutAmount',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '当月其他出库金额',
          dataIndex: 'otherOutAmount',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '终端配件一次满足率(%)',
          dataIndex: 'oneRatePart',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '当期配件工单一次满足率(%)',
          dataIndex: 'oneRateRepair',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '周转率(%)',
          dataIndex: 'turnOver',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '配件毛利润（万元）',
          dataIndex: 'partProfit',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '一年以上无动态库存金额（万元）',
          dataIndex: 'dullCostAmount',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '呆滞库存比例(%)',
          dataIndex: 'sluggishInventoryRate',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '必备库存储备率(%)',
          dataIndex: 'mustTypeRate',
          sorter: true,
          filter: true,
          filterType: 'number'
        }
      ];
    },
    selectData(val) {
      this.tableData = val;
    },
    addHandle() {
      // 新建
      this.handleType = 'add';
      this.showHandler();
    },
    closeDealerDialog() {
      this.dealerAction.visible = false;
    },
    saveDealerDialog([params]) {
      this.dealerAction.visible = false;
      this.topFilterList.find(x => x.fieldName === 'ownerCode').initialValue = params.dealerCode;
      this.topFilterList.find(x => x.fieldName === 'ownerShortName').initialValue = params.dealerShortname;
    },
    // async removeHandler() {
    //   // 删除
    //   if (!this.tableData.length) {
    //     return this.$notify({
    //       title: '提示信息',
    //       message: '请选择数据',
    //       type: 'error'
    //     });
    //   }
    //   await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   });
    //   // console.log(999);
    //   await this.deleteDialog(); // 执行删除方法
    //   // console.log(999);
    // },
    // async deleteDialog() {
    //   // 取出数据id
    //   let res = {};
    //   this.ids = this.tableData.map(x => x.qualityId); // 获取选中页面的ID加到map集合中
    //
    //   res = await deleteUsedCardQualitys({ ids: this.ids.join(',') });
    //   // alert("aaaaaa"+res);
    //   // console.log(res);
    //   // 判断结果
    //   // alert("aaaaa"+res.resultCode+"aaa");
    //   if (res.resultCode === 200) {
    //     // alert(this.res);
    //     // console.log(res.data);
    //     if (res.data) {
    //       this.fetchParams = { ...this.fetchParams }; // 重复新加载
    //
    //       return this.$notify({
    //         // 提示信息
    //         title: '提示信息',
    //         message: '删除成功',
    //         type: 'success'
    //       });
    //     }
    //   }
    // },
    // editHandle(row) {
    //   this.handleType = 'edit'; // 编辑
    //   this.formData = row;
    //   this.showHandler();
    // },
    tableChangeFun(val) {
      let userIds = val.map(item => item.createdBy).join(',');
      userIds && this.queryUserInfoByIds(userIds);
    },
    // 根据用户ids获取用户列表
    async queryUserInfoByIds(userIds) {
      let res = await getNameByIds({ userIds });
      if (res.resultCode == 200) {
        let userDicts = res.data.map(item => ({ text: item.employeeName, value: item.employeeId + '' }));
        this.columns.find(item => item.dataIndex == 'createdBy').dictItems = userDicts;
      }
    },
    changeHandle(val) {
      val.dealerCode = getOwnerCode();
      let params = Object.assign({}, val, { xhrAbort: false });
      if (params.ownerCode && params.ownerCode != null && params.ownerCode.length > 0) {
        params.ownerCode = params.ownerCode.join("','");
        params.ownerCode = "'" + params.ownerCode + "'";
      }
      this.fetchParams = params;
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    async exportHandle() {
      const [err, params] = await this.$refs.topfilter.GET_FORM_DATA();
      let map = JSON.parse(JSON.stringify(params));
      if (map.ownerCode && map.ownerCode != null && map.ownerCode.length > 0) {
        map.ownerCode = map.ownerCode.join("','");
        map.ownerCode = "'" + map.ownerCode + "'";
      }
      let date = '';
      if (map.month && map.month != null && map.month != '') {
        date = map.month.substring(0, 9);
      }
      map.dealerCode = getOwnerCode();
      await this.downHandleFile(exportMonthReportBJ, map, '配件月报(' + date + ')');
    },
    showHandler() {
      // 显示
      this.dialogTitle = `${this.conf[this.handleType]}新车保养费用申请单`;
      this.visible = true;
    },
    async getAllOwnerCode() {
      let res = await dealerInfoByAllInfo({});
      console.log(res, 'dealerInfoByAllInfo');
      let data = arrayObjDeWeight(res.data, 'dealerCode');
      this.topFilterList.find(item => item.fieldName == 'ownerCode').itemList = data.map(x => ({ text: x.dealerName, value: x.dealerCode }));
      this.columns.find(item => item.dataIndex == 'ownerName').dictItems = data.map(x => ({ text: x.dealerName, value: x.dealerCode }));
      this.columns.find(item => item.dataIndex == 'ownerName').filterItems = data.map(x => ({ text: x.dealerName, value: x.dealerCode }));
    },
    closeHandler(val, type) {
      // 关闭
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    }
  }
};
</script>

<style lang="less" scoped></style>
